#!/usr/bin/env python3
# -*- encoding: utf-8 -*-
'''
@author: yuejl
@application:
@contact: lewyuejian@163.com
@file: client.py
@time: 2021/3/16 0016 22:55
@desc:
'''
import time
import json
import requests
from requests import Request, Response
from wechatapi.models import RequestData
from loguru import logger
from wechatapi.exceptions import TestRequestDataFormatError
from typing import Dict
from requests.exceptions import (
    InvalidSchema,
    InvalidURL,
    MissingSchema,
    RequestException,
)

class ApiResponse(Response):
    def raise_for_status(self):
        if hasattr(self, "error") and self.error:
            raise self.error
        Response.raise_for_status(self)

class HttpRequest:
    def __init__(self):
        super(HttpRequest, self).__init__()
        #self.data = RequestData()
        self.params = {}
        self.session = requests.Session()

    def extract_parameters(self, url):
        """
        Aarg : 提取URL的参数

        Return: dict

        Examples:
            >>> url = 'https://www.baidu.com//s;index.php?tn=78040160_14_pg&ch=16#1'

            >>> HttpRequest().extract_parameters(url)

                {'tn': '78040160_14_pg', 'ch': '16'}

                print('scheme:', result.scheme)  # 网络协议
                print('netloc:', result.netloc)  # 域名
                print('path:', result.path)  # 文件存放路径
                print('query:', result.query)  # 查询字符
                print('params:', result.params)  # 可选参数
                print('fragment:', result.fragment)  # 拆分文档中的特殊猫
        """
        from urllib import parse
        data = {}
        if url is not None:
            temp = parse.urlparse(url).query
            if temp is not None:
                parmars = temp.split('&')
                for p in parmars:
                    print(p)
                    out = p.split('=')
                    entries = dict([(x,y) for x,y in zip(out[::2],out[1::2])])
                    data.update(entries)
        return data

    @staticmethod
    def lower_dict_keys(origin_dict):
        """ convert keys in dict to lower case

        Args:
            origin_dict (dict): mapping data structure

        Returns:
            dict: mapping with all keys lowered.

        Examples:
            >>> origin_dict = {
                "Name": "",
                "Request": "",
                "URL": "",
                "METHOD": "",
                "Headers": "",
                "Data": ""
            }
            >>> HttpRequest().lower_dict_keys(origin_dict)
                {
                    "name": "",
                    "request": "",
                    "url": "",
                    "method": "",
                    "headers": "",
                    "data": ""
                }

        """
        if not origin_dict or not isinstance(origin_dict, dict):
            return origin_dict

        return {key.lower(): value for key, value in origin_dict.items()}


    def visit_request(self, method, url, **kwargs):
        """
        发送一个HTTP请求，并捕获由于连接问题而可能发生的任何异常。
         安全模式已从请求1.x中删除

        """
        try:
            from requests.packages.urllib3.exceptions import InsecureRequestWarning
            # 禁用安全请求警告
            requests.packages.urllib3.disable_warnings(InsecureRequestWarning)

            return self.session.request(method, url, **kwargs)
        except (MissingSchema, InvalidSchema, InvalidURL):
            raise
        except RequestException as ex:
            resp = ApiResponse()
            resp.error = ex
            resp.status_code = 0  # with this status_code, content returns None
            resp.request = Request(method, url).prepare()
            return resp

    def visit_request_api(self, api_content):
        self.params["method"] = api_content.get("method")
        self.params["url"] = api_content.get("url")
        self.params["json"] = api_content.get("json")

        return requests.request(**self.params).json()


    def visit_request_api_v3(self, api_content: Dict, is_json=True, **kwargs):

        if not isinstance(api_content, Dict):
            raise TestRequestDataFormatError(
                f'Invalid request data : {api_content}'
            )

        #api_content = json.loads(api_content)
        method = api_content['method']
        url = api_content['url']
        data = api_content.get('json')
        print(type(data))

        if method in ['GET', 'get']:
            resp = self.visit_request(method=method, url=url, params=data, **kwargs)
        elif method in ['POST', 'post']:
            # 请求参数是json格式
            if is_json:
                resp = self.visit_request(method=method, url=url, json=data, verify=False, **kwargs)
            else:
                resp = self.visit_request(method=method, url=url, data=data, **kwargs)
        else:
            resp = None
        return resp.json()


    def close_session(self):
        self.session.close()

if __name__ == '__main__':
    request_params = {
        # "corpid": self.data['info'][0]['data']['request_data']['corpid'],
        # "corpsecret": self.data['info'][0]['data']['request_data']['corpsecret']
        "corpid": "wwb4f39b63b59a8a3a",
        "corpsecret": "Oyc2BalKGSP1KCmdld0P2vn-sBYsZrTGahJ8-kPxSlI"
    }
    url = "https://qyapi.weixin.qq.com/cgi-bin/gettoken"
    res = HttpRequest().visit_request(method='get',url=url,params=request_params)
    #res = HttpRequest().send_request(method='get', url=url, data=request_params)
    print(res.text)